<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <script src="../js/ajax.js"></script>
</head>

<body>

</body>
<script>
    // async函数  一般配合await关键词实现异步操作
    // 注意: 
    // a. await 必须在异步函数中使用
    // b. 异步操作必须用Promise处理好

    // 优点: 把异步操作  改的更像同步

    // T = T1 + T2 + T3
    async function fn() {
        // readText("../data/1.txt").then(text=>{}).catch()   老版本
        debugger;
        var str = "";
        var text = await readText("../data/1.txt"); // Promise实例
        console.log(text);
        str += text;

        var text = await readText("../data/2.txt"); // Promise实例
        console.log(text);
        str += text;

        var text = await readText("../data/3.txt"); // Promise实例
        console.log(text);
        str += text;

        return str;
    }
    debugger;
    var p = fn();
    p.then(str => {
        console.log(str);
    }).catch(err => {
        console.log(err);
        // throw err;
    })

    function readText(url) {
        var p = new Promise(function (resolve, reject) {
            $.ajax({
                type: "get",
                url: url,
                success: function (text) {
                    resolve(text);
                }
            })
        })
        return p; // {pending}
    }

</script>

</html>